import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformResInterceptor } from './core/interceptors/transform-res.interceptor';
import { GlobalExceptionFilter } from './core/filters/global-exceptoin.filter';
import { ValidateDtoPipe } from './core/pipes/validate-dto.pipe';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import { MyLoggerService } from '@/common/logger.service';
import { useContainer } from 'class-validator';

// import { APIPrefix } from './constants/constants'
const listening = true;
const port = process.env.PORT || 8080

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: process.env.NODE_ENV === 'dev' ? new Logger() : false,
  });

  const configService: ConfigService = app.get(ConfigService);
  const myLoggerService: MyLoggerService = app.get(MyLoggerService);

  myLoggerService.info({
    message: 'Starting Nest application...',
    data: {
      NODE_ENV: process.env.NODE_ENV,
      port: configService.get('app.port'),
    },
  });

  // 设置所有 api 访问前缀
  // app.setGlobalPrefix(APIPrefix)
  app.enableCors();
  app.useGlobalPipes(new ValidateDtoPipe(configService));
  app.useGlobalInterceptors(new TransformResInterceptor(myLoggerService));
  app.useGlobalFilters(new GlobalExceptionFilter(myLoggerService));
  app.setGlobalPrefix(configService.get('app.globalPerfix')) //添加全局路由前缀 api/v1

  useContainer(app.select(AppModule), { fallbackOnErrors: true });

  if (listening) {
    await app.listen(port);
    myLoggerService.info({
      message: 'Nest application successfully started',
    });
  }
}
bootstrap();
